<template>
  <div class="custom-file">
    <input
      type="file"
      class="custom-file-input"
      id="customFile"
      @change="uploadFile()"
    />
    <label class="custom-file-label">{{ img_name }}</label>
  </div>
</template>

<script>
import COS from "cos-js-sdk-v5";
import axios from "axios";

export default {
  name: "InputUploadImg",
  data() {
    return {
      img_name: "请选择文件",
    };
  },
  methods: {
    uploadFile() {
      let result = Object;
      var fileObj = document.getElementById("customFile").files[0];
      let m_this = this;
      // console.log(fileObj);

      axios.post("/api/COS/getToken?name=" + fileObj.name).then((data) => {
        result = data.data;
        var cos = new COS({
          // 必选参数
          getAuthorization: function (options, callback) {
            callback({
              TmpSecretId: result.Credentials.TmpSecretId,
              TmpSecretKey: result.Credentials.TmpSecretKey,
              XCosSecurityToken: result.Credentials.Token,
              StartTime: result.StartTime, // 时间戳，单位秒，如：1580000000
              ExpiredTime: result.ExpiredTime, // 时间戳，单位秒，如：1580000900
            });
          },
        });
        cos.putObject(
          {
            Bucket: "myblog-1302916147" /* 必须 */,
            Region: "ap-guangzhou" /* 存储桶所在地域，必须字段 */,
            Key: result.Time + "/" + result.Name /* 必须 */,
            StorageClass: "STANDARD",
            Body: fileObj, // 上传文件对象
            onProgress: function (progressData) {
              console.log(JSON.stringify(progressData));
            },
          },
          function (err, data) {
            // console.log(err || data);
            m_this.img_name = fileObj.name;
            m_this.$emit("transmitName", result.Time + "/" + result.Name);
          }
        );
      });
    },
  },
};
</script>

<style>
</style>